package com.qf.air.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.air.entity.Air;
import com.qf.air.enums.AirEnum;
import com.qf.air.exception.AirEx;
import com.qf.air.mapper.AirMapper;
import com.qf.air.service.AirService;
import com.qf.air.util.ElasticsearchUtil;
import com.qf.air.util.JSONUtil;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryRequest;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Author: llf
 * @Date: 2021/11/4 21:02
 */
@Service
public class AirServiceImpl implements AirService {

    private String index = "air";

    @Autowired
    private AirMapper airMapper;

    @Override
    public PageInfo<Air> findByPageAndDistrictId(Integer page, Integer rows, Integer districtId, String monitoringStation, Date startTime, Date endTime) {
        PageHelper.startPage(page,rows);
        SearchRequest request = new SearchRequest();
        request.indices("air");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(QueryBuilders.matchAllQuery());
        sourceBuilder.size(1000);
        if(districtId != null && districtId != 0){
            sourceBuilder.query(QueryBuilders.termQuery("districtId", districtId));
        }
        if(!StringUtils.isEmpty(monitoringStation)){
            sourceBuilder.query(QueryBuilders.matchQuery("monitoringStation",monitoringStation));
            HighlightBuilder builder = new HighlightBuilder();
            builder.preTags("<span style='color:red'>");
            builder.postTags("</span>");
            builder.field("monitoringStation");
            sourceBuilder.highlighter(builder);
        }
        if(startTime != null){
            sourceBuilder.query(QueryBuilders.rangeQuery("monitorTime").gte(startTime));
        }
        if(endTime != null){
            sourceBuilder.query(QueryBuilders.rangeQuery("lastModifyTime").lte(endTime));
        }
        request.source(sourceBuilder);
        SearchResponse resp = null;
        try {
            resp = ElasticsearchUtil.getClient().search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new AirEx("查询失败", 530);
        }
        List<Air> airs = new ArrayList<>();
        for (SearchHit hit : resp.getHits().getHits()) {
            String json = hit.getSourceAsString();
            Air air = JSONUtil.json2Obj(json, Air.class);

            airs.add(air);
            HighlightField field = hit.getHighlightFields().get("monitoringStation");
            if(field != null){
                String value = field.getFragments()[0].toString();
                air.setMonitoringStation(value);
            }
        }
        PageInfo<Air> pageInfo = new PageInfo<>(airs);
        return pageInfo;
    }

//    @Override
//    public PageInfo<Air> findByPageAndDistrictId(Integer page, Integer rows, Integer districtId, String monitoringStation, Date startTime, Date endTime) {
//        PageHelper.startPage(page,rows);
//        List<Air> all = airMapper.findByDistrictId(districtId,monitoringStation,startTime,endTime);
//        PageInfo<Air> pageInfo = new PageInfo<>(all);
//        return pageInfo;
//    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void save(Air air) {
        Integer count = airMapper.save(air);
        if(count !=1){
            //添加失败，记录日志，抛出异常
            System.out.println("添加信息失败！ air="+air);
            throw new AirEx(AirEnum.AIR_ADD_ERROR);
        }
        IndexRequest request = new IndexRequest();
        request.index(index);
        Air air1 = airMapper.selectById(air.getId());
        request.source(JSONUtil.obj2JSON(air1), XContentType.JSON);
        try {
            IndexResponse resp = ElasticsearchUtil.getClient().index(request, RequestOptions.DEFAULT);
            if ("CREATED".equalsIgnoreCase(resp.getResult().getLowercase())) {
                System.out.println("添加文档成功！");
            }else{
                System.out.println("文档添加失败！");
            }
        } catch (IOException e) {
            throw new AirEx("文档添加失败",531);
        }
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout = -1,readOnly = false,rollbackFor = Exception.class,noRollbackFor = ArithmeticException.class)
    public void deleteById(Integer id) {
        int i = airMapper.deleteById(id);

        if(i!=1){
            System.out.println("删除失败！ id="+id);
            throw new AirEx(AirEnum.AIR_DELETE_ERROR);
        }
        //默认删除文档id
//        DeleteRequest request = new DeleteRequest();
//        request.index(index);
//        request.(String.valueOf(id));
        //自定义删除
        DeleteByQueryRequest request = new DeleteByQueryRequest();
        request.indices(index);
        request.setQuery(QueryBuilders.termQuery("id",id));
        try {
            BulkByScrollResponse response = ElasticsearchUtil.getClient().deleteByQuery(request, RequestOptions.DEFAULT);
//            System.out.println(response);
        } catch (IOException e) {
            throw new AirEx("文档删除失败",532);
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateById(Air air) {
        int count = airMapper.updateById(air);
        if(count!=1){
            System.out.println("修改失败！ air="+air);
            throw new AirEx(AirEnum.AIR_UPDATE_ERROR);
        }
        Air air1 = airMapper.selectById(air.getId());
        UpdateRequest request = new UpdateRequest();
        request.index(index);
        request.id(String.valueOf(air.getId()));
        request.doc(JSONUtil.obj2JSON(air1),XContentType.JSON);
        try {
            UpdateResponse response = ElasticsearchUtil.getClient().update(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new AirEx("文档修改失败",533);
        }
    }
}
